package com.kp.fintech.oauth.service.impl;


import com.kp.fintech.oauth.vo.UserLoginBean;
import com.kp.fintech.oauth.security.JwtAuthenticatioToken;
import com.kp.fintech.oauth.service.OauthTokenService;
import com.kp.fintech.oauth.util.JwtTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@PropertySource({"classpath:application-officedev.yml"}) //读取配置文件
@Service
public class OauthTokenServiceImpl implements OauthTokenService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${token.valid-time}")
    private  String tokenValidTime ;

    @Override
    public String getTockenNo(UserLoginBean userLoginBean) {

        JwtAuthenticatioToken token = new JwtAuthenticatioToken(userLoginBean.getAccount(), userLoginBean.getPassword());
        // 生成令牌号并返回
        String strToken = JwtTokenUtils.generateToken(userLoginBean.getAccount());

        Map<String,Object> redisMap =  new HashMap();
        redisMap.put("userName",userLoginBean.getAccount());
        redisMap.put("sessionId",userLoginBean.getSessionId());
        redisMap.put("tokenNo",strToken);
        redisMap.put("remoteAddress",userLoginBean.getRemoteAddress());
        redisMap.put("timeStamp",System.currentTimeMillis());

        //以tokenNo作为key并将redisMap保存到到redis中,时效为20小时
        try {
            redisTemplate.opsForHash().putAll(strToken,redisMap);
            redisTemplate.expire(strToken,Long.parseLong(tokenValidTime), TimeUnit.MINUTES);
        } catch (Exception e) {
            return null;
        }

        return strToken;
    }

    public Boolean refreshToken(String tokenNo){
        return redisTemplate.expire(tokenNo,Long.parseLong(tokenValidTime), TimeUnit.MINUTES);
    }

    @Override
    public Boolean validateToken(String tokenNO, String userName) {
        return JwtTokenUtils.validateToken(tokenNO,userName);
    }


}
